import threading
import time
import json
'''
    APP的父类,所有的APP必须实现该类
    @author warren
'''


class ParentApp:

    def __init__(self):
        self.app_name = 'parent-app'
        self.call_stream = True

    def get_app_name(self):  # 获取app名称，抽象方法
        return self.app_name

    def get_call_stream(self):
        return self.call_stream

    def get_msgs_list(self, local_data):  # 发送给大模型的messages
        msgs_list = []
        messages = []
        user_prompt_s, sys_prompt_s = self.reload_user_prompt(local_data), self.reload_sys_prompt(local_data)
        max_len = len(user_prompt_s) if len(user_prompt_s) > len(sys_prompt_s) else len(sys_prompt_s)
        for i in range(0, max_len):
            user_prompt = user_prompt_s[i] if i < len(user_prompt_s) else '请认真作答'
            sys_prompt = sys_prompt_s[i] if i < len(sys_prompt_s[i]) else '请认真作答'
            user_msg = {
                'role': 'user',
                'content': user_prompt
            }

            sys_msg = {
                'role': 'system',
                'content': sys_prompt
            }
            messages.append(user_msg)
            messages.append(sys_msg)
            msgs_list.append([self.call_back_before(), messages, self.call_back_after()])
        return msgs_list

    def reload_user_prompt(self, local_data):
        user_prompt = local_data['user_prompt']
        local_data['user_prompt'] = [user_prompt]
        return [user_prompt]



    def reload_sys_prompt(self, local_data):
        user_prompt = local_data['sys_prompt']
        local_data['sys_prompt'] = [user_prompt]
        return [user_prompt]


    def call_back_before(self):
        return None

    def call_back_after(self):
        return None

    def resolve_completion(self, completion, chat_id, is_stop, model):
        content = extract_content(completion, self.call_stream)
        return self.create_proxy_response(content, chat_id, True, is_stop, model)


    def create_proxy_response(self,content, chat_id, is_stream, is_stop, model):
        message = {
            "id": chat_id,
            "choices": [{
                "delta": {
                    "content": content,
                    "function_call": None,
                    "role": "assistant",
                    "tool_calls": None
                },
                "finish_reason": 'stop' if is_stop else None,
                "index": 0,
                "logprobs": None
            }],
            "created": int(time.time()),
            "model": f"{model}",
            "object": "chat.completion.chunk",
            "system_fingerprint": None,
            "usage": None  # 根据需要添加 usage 字段
        }
        # 将消息转换为 JSON 字符串并发送
        json_message = json.dumps(message)
        return f"data: {json_message}\n\n"

    def create_end_sse_response(self, chat_id, is_stream, model):
        return self.create_proxy_response('\n',chat_id,is_stream,True,model)

def extract_content(data,is_stream):
    s = ""
    try:
        for choice in data.choices:
            if is_stream:
                s += choice.delta.content
            else:
                s += choice.message.content
    except KeyError:
        return s
    return s
